<template>
  <div class="advanced-top-nav" :style="{'--theme': theme}">
    <div class="logo-container">
      <router-link to="/" class="logo-link">
        <img src="@/assets/logo/logo.png" alt="Logo" class="logo-img">
        <span class="logo-title" v-if="!isCollapse">智慧环境监测系统</span>
      </router-link>
    </div>
    
    <div class="menu-container" ref="menuContainer">
      <ul class="main-menu">
        <li 
          v-for="(item, index) in mainMenus" 
          :key="index" 
          class="menu-item"
          :class="{'active': isActive(item)}"
          @mouseenter="showSubmenu(item, index)"
          @mouseleave="hideSubmenu"
        >
          <router-link :to="item.path" class="menu-link">
            <svg-icon 
              v-if="item.meta && item.meta.icon && item.meta.icon !== '#'" 
              :icon-class="item.meta.icon" 
              class="menu-icon"
            />
            <span class="menu-text">{{ item.meta.title }}</span>
            <i v-if="item.children && item.children.length > 0" class="el-icon-arrow-down menu-arrow"></i>
          </router-link>
          
          <!-- 子菜单 -->
          <transition name="dropdown-fade">
            <div 
              v-if="item.children && item.children.length > 0 && currentSubmenuIndex === index" 
              class="submenu"
              :style="submenuStyle"
            >
              <div class="submenu-content">
                <div v-if="item.meta && item.meta.title" class="submenu-header">
                  <h3>{{ item.meta.title }}</h3>
                  <p v-if="item.meta.description">{{ item.meta.description }}</p>
                </div>
                <ul class="submenu-list">
                  <li 
                    v-for="(child, childIndex) in item.children" 
                    :key="childIndex"
                    class="submenu-item"
                    @click="navigateTo(child)"
                  >
                    <div class="submenu-item-content">
                      <svg-icon 
                        v-if="child.meta && child.meta.icon && child.meta.icon !== '#'" 
                        :icon-class="child.meta.icon" 
                        class="submenu-icon"
                      />
                      <div class="submenu-info">
                        <h4>{{ child.meta.title }}</h4>
                        <p v-if="child.meta.description">{{ child.meta.description }}</p>
                      </div>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
          </transition>
        </li>
      </ul>
    </div>
    
    <div class="right-menu">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索菜单..."
          prefix-icon="el-icon-search"
          @focus="showSearchResults = true"
          @blur="hideSearchResults"
          @input="handleSearch"
          clearable
        >
        </el-input>
        <transition name="dropdown-fade">
          <div v-if="showSearchResults && searchResults.length > 0" class="search-results">
            <div 
              v-for="(result, index) in searchResults" 
              :key="index"
              class="search-result-item"
              @click="navigateTo(result)"
            >
              <svg-icon 
                v-if="result.meta && result.meta.icon && result.meta.icon !== '#'" 
                :icon-class="result.meta.icon" 
                class="result-icon"
              />
              <span class="result-title">{{ result.meta.title }}</span>
            </div>
          </div>
        </transition>
      </div>
      
      <el-tooltip content="全屏" effect="dark" placement="bottom">
        <div class="right-menu-item" @click="toggleFullScreen">
          <svg-icon icon-class="fullscreen" />
        </div>
      </el-tooltip>
      
      <el-tooltip content="主题设置" effect="dark" placement="bottom">
        <div class="right-menu-item" @click="openThemeSettings">
          <svg-icon icon-class="theme" />
        </div>
      </el-tooltip>
      
      <el-dropdown class="avatar-container" trigger="hover">
        <div class="avatar-wrapper">
          <img :src="avatar" class="user-avatar">
          <span class="user-nickname">{{ nickName }}</span>
          <i class="el-icon-caret-bottom"></i>
        </div>
        <el-dropdown-menu slot="dropdown">
          <router-link to="/user/profile">
            <el-dropdown-item>个人中心</el-dropdown-item>
          </router-link>
          <el-dropdown-item @click.native="openThemeSettings">
            <span>主题设置</span>
          </el-dropdown-item>
          <el-dropdown-item divided @click.native="logout">
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { isHttp } from '@/utils/validate'
import Screenfull from '@/components/Screenfull'

export default {
  name: 'AdvancedTopNav',
  components: {
    Screenfull
  },
  data() {
    return {
      currentSubmenuIndex: -1,
      submenuStyle: {},
      searchKeyword: '',
      searchResults: [],
      showSearchResults: false
    }
  },
  computed: {
    ...mapGetters([
      'sidebarRouters',
      'avatar',
      'nickName'
    ]),
    theme() {
      return this.$store.state.settings.theme
    },
    isCollapse() {
      return !this.$store.state.app.sidebar.opened
    },
    // 主菜单项
    mainMenus() {
      let menus = []
      this.sidebarRouters.map((menu) => {
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === '/' && menu.children) {
            menus.push(menu.children[0])
          } else {
            menus.push(menu)
          }
        }
      })
      return menus
    },
    // 所有菜单项（用于搜索）
    allMenus() {
      let allMenus = []
      
      // 递归获取所有菜单项
      const getAllMenus = (menus, parent = null) => {
        menus.forEach(menu => {
          if (menu.hidden !== true) {
            // 设置父路径
            if (parent) {
              menu.parentPath = parent.path
            }
            
            allMenus.push(menu)
            
            if (menu.children && menu.children.length > 0) {
              getAllMenus(menu.children, menu)
            }
          }
        })
      }
      
      getAllMenus(this.sidebarRouters)
      return allMenus
    }
  },
  methods: {
    // 显示子菜单
    showSubmenu(item, index) {
      if (item.children && item.children.length > 0) {
        this.currentSubmenuIndex = index
        
        // 计算子菜单位置
        this.$nextTick(() => {
          const menuItem = this.$refs.menuContainer.querySelectorAll('.menu-item')[index]
          if (menuItem) {
            const rect = menuItem.getBoundingClientRect()
            this.submenuStyle = {
              left: `${rect.left}px`,
              top: `${rect.bottom}px`
            }
          }
        })
      }
    },
    // 隐藏子菜单
    hideSubmenu() {
      this.currentSubmenuIndex = -1
    },
    // 判断菜单项是否激活
    isActive(item) {
      const path = this.$route.path
      if (path.startsWith(item.path)) {
        return true
      }
      return false
    },
    // 导航到指定路由
    navigateTo(item) {
      if (isHttp(item.path)) {
        // http(s):// 路径新窗口打开
        window.open(item.path, "_blank")
      } else {
        if (item.query) {
          let query = JSON.parse(item.query)
          this.$router.push({ path: item.path, query: query })
        } else {
          this.$router.push({ path: item.path })
        }
      }
      
      // 隐藏搜索结果
      this.showSearchResults = false
      this.searchKeyword = ''
    },
    // 搜索菜单
    handleSearch() {
      if (!this.searchKeyword) {
        this.searchResults = []
        return
      }
      
      this.searchResults = this.allMenus.filter(item => {
        return item.meta && 
               item.meta.title && 
               item.meta.title.toLowerCase().includes(this.searchKeyword.toLowerCase())
      }).slice(0, 5) // 限制搜索结果数量
    },
    // 隐藏搜索结果
    hideSearchResults() {
      setTimeout(() => {
        this.showSearchResults = false
      }, 200)
    },
    // 切换全屏
    toggleFullScreen() {
      if (!screenfull.isEnabled) {
        this.$message({
          message: '你的浏览器不支持全屏',
          type: 'warning'
        })
        return false
      }
      screenfull.toggle()
    },
    // 打开主题设置
    openThemeSettings() {
      this.$emit('setLayout')
    },
    // 退出登录
    logout() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index'
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.advanced-top-nav {
  display: flex;
  align-items: center;
  height: 60px;
  padding: 0 20px;
  background: linear-gradient(135deg, #ffffff 0%, #f5f7fa 100%);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1000;
  
  .logo-container {
    flex-shrink: 0;
    margin-right: 40px;
    
    .logo-link {
      display: flex;
      align-items: center;
      text-decoration: none;
      
      .logo-img {
        width: 40px;
        height: 40px;
        margin-right: 10px;
      }
      
      .logo-title {
        font-size: 20px;
        font-weight: 600;
        color: var(--theme, #409EFF);
      }
    }
  }
  
  .menu-container {
    flex: 1;
    position: relative;
    
    .main-menu {
      display: flex;
      list-style: none;
      margin: 0;
      padding: 0;
      
      .menu-item {
        position: relative;
        margin-right: 5px;
        
        .menu-link {
          display: flex;
          align-items: center;
          padding: 0 15px;
          height: 60px;
          text-decoration: none;
          color: #606266;
          transition: all 0.3s;
          border-radius: 4px;
          
          .menu-icon {
            margin-right: 8px;
            font-size: 18px;
          }
          
          .menu-text {
            font-size: 15px;
            font-weight: 500;
          }
          
          .menu-arrow {
            margin-left: 5px;
            font-size: 12px;
            transition: transform 0.3s;
          }
        }
        
        &:hover {
          .menu-link {
            color: var(--theme, #409EFF);
            background-color: rgba(64, 158, 255, 0.1);
          }
        }
        
        &.active {
          .menu-link {
            color: var(--theme, #409EFF);
            background-color: rgba(64, 158, 255, 0.1);
          }
        }
      }
    }
  }
  
  .right-menu {
    display: flex;
    align-items: center;
    
    .search-box {
      position: relative;
      margin-right: 15px;
      
      .el-input {
        width: 200px;
      }
      
      .search-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        max-height: 300px;
        overflow-y: auto;
        z-index: 1000;
        
        .search-result-item {
          display: flex;
          align-items: center;
          padding: 10px 15px;
          cursor: pointer;
          transition: background-color 0.3s;
          
          .result-icon {
            margin-right: 10px;
            color: #909399;
          }
          
          .result-title {
            font-size: 14px;
          }
          
          &:hover {
            background-color: #f5f7fa;
          }
        }
      }
    }
    
    .right-menu-item {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      height: 40px;
      margin-right: 10px;
      cursor: pointer;
      border-radius: 50%;
      transition: all 0.3s;
      
      &:hover {
        background-color: rgba(64, 158, 255, 0.1);
        color: var(--theme, #409EFF);
      }
    }
    
    .avatar-container {
      margin-right: 0;
      
      .avatar-wrapper {
        display: flex;
        align-items: center;
        cursor: pointer;
        
        .user-avatar {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          margin-right: 8px;
        }
        
        .user-nickname {
          font-size: 14px;
          font-weight: 500;
          margin-right: 5px;
        }
        
        .el-icon-caret-bottom {
          font-size: 12px;
        }
      }
    }
  }
}

// 子菜单样式
.submenu {
  position: fixed;
  z-index: 1000;
  background: white;
  border-radius: 8px;
  box-shadow: 0 8px 24px 0 rgba(0, 0, 0, 0.12);
  padding: 20px;
  min-width: 300px;
  max-width: 500px;
  
  .submenu-content {
    .submenu-header {
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #f0f0f0;
      
      h3 {
        margin: 0 0 5px 0;
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
      
      p {
        margin: 0;
        font-size: 12px;
        color: #909399;
      }
    }
    
    .submenu-list {
      list-style: none;
      margin: 0;
      padding: 0;
      
      .submenu-item {
        margin-bottom: 8px;
        cursor: pointer;
        border-radius: 4px;
        transition: background-color 0.3s;
        
        .submenu-item-content {
          display: flex;
          align-items: center;
          padding: 8px 10px;
          
          .submenu-icon {
            width: 20px;
            height: 20px;
            margin-right: 10px;
            color: #909399;
          }
          
          .submenu-info {
            h4 {
              margin: 0 0 2px 0;
              font-size: 14px;
              font-weight: 500;
              color: #303133;
            }
            
            p {
              margin: 0;
              font-size: 12px;
              color: #909399;
            }
          }
        }
        
        &:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }
}

// 动画效果
.dropdown-fade-enter-active, .dropdown-fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.dropdown-fade-enter, .dropdown-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>